<template>
	<a-select v-model:value="selectLabel" v-bind="option">
		<template #dropdownRender="{menuNode}">
			<component v-if="leftOptions.length === 0 && rightOptions.length === 0" :is="menuNode" />
			<div class="display-flex" style="padding: 0 16px">
				<div class="flex-1">
					<template v-if="leftOptions.length > 0">
						<a-typography-paragraph strong><blockquote>优惠活动</blockquote></a-typography-paragraph>
						<a-checkbox-group @click.stop :value="selectLeft.value" name="left" @change="checkboxoChange">
							<a-checkbox
								v-for="item in leftOptions"
								:key="item.value"
								:disabled="item.disabled"
								:style="radioStyle"
								:value="item.value">
								<div class="display-flex" :class="{disabled: item.disabled}">
									<span class="active-name">{{ item.label }}</span>
									<span class="active-type">{{ Boolean(item.dataSource?.isUse) ? '可以叠加' : '不可叠加' }}</span>
									<a-tooltip color="#fff" placement="topLeft">
										<a-typography-text ellipsis :content="getActivityDesc(item.dataSource)"></a-typography-text>
										<template #title>
											<a-typography-text>{{ getActivityDesc(item.dataSource) }}</a-typography-text>
										</template>
									</a-tooltip>
								</div>
							</a-checkbox>
						</a-checkbox-group>
						<!-- <a-radio-group :value="selectLeft.value" name="left" @change="e => radioChange(e, 0)">
							<a-radio v-for="item in leftOptions" :key="item.value" :disabled="item.disabled" :style="radioStyle" :value="item.value">{{ item.label }}</a-radio>
						</a-radio-group> -->
					</template>
				</div>
				<a-divider type="vertical" style="height: auto; padding: 0 10px" />
				<div class="flex-1">
					<template v-if="rightOptions.length > 0">
						<a-typography-paragraph strong><blockquote>付款优惠</blockquote></a-typography-paragraph>
						<a-radio-group @click.stop :value="selectRight.value" name="right" @change="radioChange">
							<a-radio
								v-for="item in rightOptions"
								:key="item.value"
								:disabled="item.disabled"
								:style="radioStyle"
								:value="item.value">
								<div class="display-flex" :class="{disabled: item.disabled}">
									<span class="active-name">{{ item.label }}</span>
									<a-tooltip color="#fff" placement="topLeft">
										<a-typography-text ellipsis :content="getActivityDesc(item.dataSource)"></a-typography-text>
										<template #title>
											<a-typography-text>{{ getActivityDesc(item.dataSource) }}</a-typography-text>
										</template>
									</a-tooltip>
								</div>
							</a-radio>
						</a-radio-group>
					</template>
				</div>
			</div>
			<a-divider class="margin-none" />
			<vxe-toolbar @click.stop>
				<template #tools>
					<a-button type="default" @click="onFold">关闭</a-button>
				</template>
			</vxe-toolbar>
		</template>
	</a-select>
</template>
<script lang="ts" setup>
	import {reactive, ref, watch, nextTick, onUnmounted, onMounted} from 'vue'
	import {RadioChangeEvent, message} from 'ant-design-vue'
	import {DictConfig} from '@/interface/interface'

	const props = defineProps<{
		/** 父组件v-modal语法糖绑定字段 */
		value: Array<string>
		/** 左侧数据源 */
		leftOptions: any[]
		// /** 右侧数据源 */
		rightOptions: any[]
	}>()

	const timer = ref<NodeJS.Timeout>()
	onUnmounted(() => clearTimeout(timer.value))
	const option = reactive({
		open: false,
		showSearch: false,
		placeholder: '请选择活动',
		dropdownClassName: 'two-columns-select',
		mode: 'multiple',
		getPopupContainer(triggerNode: HTMLDivElement) {
			return triggerNode ? triggerNode.parentNode : document.body
		},
		onFocus() {
			timer.value = setTimeout(() => (option.open = true), 100)
		},
		onChange(arr: string[]) {
			selectChange(arr)
		},
		onClear() {
			onClear()
		}
	})

	const leftOptions = ref<any>([])
	watch(
		() => props.leftOptions,
		(list: any[]) => (leftOptions.value = list),
		{
			deep: true
		}
	)
	const rightOptions = ref<any>([])
	watch(
		() => props.rightOptions,
		(list: any[]) => (rightOptions.value = list),
		{
			deep: true
		}
	)
	// eslint-disable-next-line no-unused-vars
	const emits = defineEmits<{
		(e: 'update:value', value: Array<string | number>): void
	}>()
	/** a-radio-group v-bind:value 下标取selectValue值  */
	let selectLeft = reactive<{
		label: string[]
		value: string[]
	}>({
		label: [],
		value: []
	})
	let selectRight = reactive<DictConfig>({
		label: '',
		value: ''
	})
	/** a-radio-group v-bind:value 下标交换位置 */
	const radioStyle = reactive({
		display: 'flex',
		height: '30px',
		lineHeight: '30px',
		margin: 0
	})
	/** update返回值 */
	const selectValue = ref<Array<string | number>>([])
	/** 页面展示汉字 */
	const selectLabel = ref<Array<string>>([])
	// 清空
	const onClear = () => {
		selectValue.value = []
		selectLabel.value = []
		selectLeft = {
			label: [],
			value: []
		}
		selectRight = {
			label: '',
			value: ''
		}
		leftOptions.value.forEach(item => {
			item.checked = false
		})
		rightOptions.value.forEach(item => {
			item.checked = false
		})
		emits('update:value', selectValue.value)
	}
	const getActivityDesc = (data: any) => {
		const {useThreshold, detailedTimePeriod, type, payDiscount, discountAmount} = data
		if (type === 4) {
			const obj = JSON.parse(payDiscount)
			return `季付${obj.quarterlyPayment}%，半年付${obj.semiAnnualPayment}%，年付${obj.annualPayment}%`
		} else {
			return (
				`签约≥${useThreshold}个月` +
				`，${
					detailedTimePeriod === 0
						? '租期内'
						: detailedTimePeriod > 0
						? `后${Math.abs(detailedTimePeriod)}个月`
						: `前${Math.abs(detailedTimePeriod)}个月`
				}` +
				`，租金${type === 1 ? '立减' : '折扣'}` +
				`${discountAmount}` +
				`${type === 1 ? '元' : type === 2 ? '%' : ''}`
			)
		}
	}
	// 回显数据
	const onInit = () => {
		nextTick(() => {
			props.value.forEach(id => {
				leftOptions.value.forEach(v => {
					if (v.value === id) {
						v.checked = true
						selectLeft.label.push(v.label)
						selectLeft.value.push(v.value)
					}
				})
				rightOptions.value.forEach(v => {
					if (v.value === id) {
						v.checked = true
						selectRight.label = v.label
						selectRight.value = v.value
					}
				})
			})
			updateData()
		})
	}

	const selectChange = (arr: string[]) => {
		console.log('selectChange arr', arr)

		let leftSelected: any = []
		if (arr.length === 0) {
			selectLeft = {label: [], value: []}
			selectRight = {label: '', value: ''}
		} else {
			arr.forEach((str: any) => {
				const left = leftOptions.value.find(v => v.label === str)
				left && leftSelected.push(left)

				const rightSelected = props.rightOptions.find(v => v.label === str)
				selectRight = {
					value: rightSelected?.value ?? '',
					label: rightSelected?.label ?? ''
				}
			})
		}
		console.log('leftSelected arr', leftSelected)

		checkboxoChange(leftSelected.map(v => v.value))
	}

	const onFold = () => {
		option.open = false
	}

	const getArrDifference = (arr1, arr2) => {
		return arr1.concat(arr2).filter((v, i, arr) => {
			return arr.indexOf(v) === arr.lastIndexOf(v)
		})
	}
	// type = 2集合 里面的 detailedTimePeriod 不一样不能选
	const tempFn = (current: any) => {
		if (current.dataSource?.type === 2) {
			const type2List = leftOptions.value.filter(item => item.checked && item.dataSource?.type === 2)
			console.log('type2List', type2List)
			console.log('current', current)
			const pass = type2List.some(v => v.dataSource?.detailedTimePeriod !== current.dataSource?.detailedTimePeriod)
			if (pass) {
				leftOptions.value.forEach(item => {
					if (item.value === current.value) item.checked = false
				})
				message.info('折扣使用月份不一致，不可叠加使用')
			}
		}
	}
	// 下拉框左边
	const checkboxoChange = (e: string[]) => {
		const dif = getArrDifference(e, selectLeft.value)
		console.log('checkboxoChange e', e)
		console.log('checkboxoChange selectLeft', selectLeft.value)
		console.log('checkboxoChange dif', dif)

		if (dif.length > 0) {
			const leftSelected = leftOptions.value.find(v => v.value === dif[0])
			console.log('checkboxoChange leftSelected', leftSelected)
			if (e.length < selectLeft.value.length) {
				// 取消选中
				leftSelected.checked = false
				const list = leftOptions.value.filter(item => item.checked)
				selectLeft = {
					value: list.map(item => item.value),
					label: list.map(item => item.label)
				}
			} else if (leftSelected?.dataSource.isUse !== 1) {
				// 单选
				leftOptions.value.forEach(item => {
					if (item.value !== dif[0]) item.checked = false
				})
				selectLeft = {
					value: dif,
					label: [leftSelected?.label as string]
				}
			} else {
				// 多选
				leftOptions.value.forEach(item => {
					if (item.dataSource.isUse !== 1) item.checked = false
					if (item.value === dif[0]) item.checked = true
				})
				tempFn(leftSelected)
				const list = leftOptions.value.filter(item => item.checked)
				selectLeft = {
					value: list.map(item => item.value),
					label: list.map(item => item.label)
				}
			}
		} else {
			// 否则清空
			selectLeft = {
				label: [],
				value: []
			}
			leftOptions.value.forEach(item => {
				item.checked = false
			})
		}

		updateData()
	}
	// 下拉框 右边
	const radioChange = (e: RadioChangeEvent) => {
		const {value} = e.target
		if (!value) return
		const rightSelected = rightOptions.value.find(v => v.value === value)
		selectRight = {
			value,
			label: rightSelected?.label ?? ''
		}
		updateData()
	}
	const updateData = () => {
		selectValue.value = [...selectLeft.value, selectRight.value].filter(v => Boolean(v))
		selectLabel.value = [...selectLeft.label, selectRight.label].filter(v => Boolean(v))
		emits('update:value', selectValue.value)
	}

	defineExpose({
		onClear,
		onInit,
		onFold
	})

	onMounted(() => document.addEventListener('click', onFold))
	onUnmounted(() => document.removeEventListener('click', onFold))
</script>

<style lang="less" scoped>
	.two-columns-select {
		position: relative;
		width: 100%;
	}
	.select-item {
		min-height: 30px;
	}

	.flex-1 {
		flex: 1;
		overflow: hidden;
	}

	.disabled {
		span {
			color: rgba(0, 0, 0, 0.25) !important;
		}
	}
	.ant-checkbox-group,
	.ant-radio-group {
		width: 100%;
		max-height: 220px;
		overflow-y: auto;
	}
	:deep(.ant-checkbox-wrapper),
	:deep(.ant-radio-wrapper) {
		> span:last-child {
			overflow: hidden;
		}
	}
	.active-name {
		display: inline-block;
		min-width: 150px;
		font-weight: 700;
	}
	.active-type {
		display: inline-block;
		min-width: 70px;
	}
</style>
